package com.example.woke;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Key;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.MediaStoreSignature;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.method.Intentnet;
import com.woke.method.MyApp;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;

public class RegisterActivity extends Activity implements OnClickListener  {

	long lastClick = 0;
	int user_from = 1;// 用于判断是哪个OEM，1表示默认中财。
	private TextView mTcode,mTok;
	private EditText mEphone;
	private EditText mEokcode;
	private EditText mEpsw,mEdoublepsw;
	private ArrayList<String> list = new ArrayList<String>();
	private boolean qiyeornot ; //�ж���ҵ�����
	private int jtime = 60;
	private Runnable runnableRef = new Runnable() {  
        public void run() {  
        	
        	if(jtime == 0){
        		Message msg = new Message();
        		msg.what = 911 ;
        		mHandler.sendMessage(msg);
        		mHandler.removeCallbacks(runnableRef); 
        	}else{
        		jtime = jtime - 1;
        		Message msg = new Message();
        		msg.what = 109 ;
        		mHandler.sendMessage(msg);
        	}
        	
        	mHandler.postDelayed(runnableRef, 1000);  
        }  
    };  
    
    Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == 911){
				mTcode.setText("点击发送验证码");
				mHandler.removeCallbacks(runnableRef);
				jtime = 60;
				mTcode.setClickable(true);
				mTcode.setBackgroundResource(R.drawable.rect_lightred);
			}else if(msg.what == 109){
				mTcode.setText("("+jtime+")秒后重新发送");
				mTcode.setBackgroundResource(R.drawable.rect_lightgray);
				mTcode.setClickable(false);
			}else if(msg.what == 1){
//				mBar.startAnimation(
//						AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.btn_rotate));
				mRelativ.setVisibility(View.VISIBLE);
			}else if(msg.what == 2){
//				mBar.clearAnimation();
				mRelativ.setVisibility(View.GONE);
			}
		}
	};
//	private ProgressBar mBar;
	private Intentnet net;
	private MyApp myapp;
	private String getregid;
	private RelativeLayout mRelativ;
	private View mLinear;
	private RelativeLayout mRel_gren,mRel_qiye;
	private TextView mT1;
	private TextView mT2;
	private ImageView mIg1;
	private ImageView mIg2,imageCode;
	private View showview,showview1;
	private EditText mEyaoqing,mEbankno,mEkaihuhang,mEqiyename,mEzhizhao,editimageCode;
	private String yaoqing;
	private String bnkno;
	private String kaihuhang;
	private String qiyename;
	private String zhizhao;
	private String psws;
	private EditText mEnamesd;
	private String user_nicename;
	String registrationID;
	Dialog mydialog;

	AlertDialog alertDialog ;
	private AlertView mAlertView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		registrationID = JPushInterface.getRegistrationID(RegisterActivity.this);
		myapp = (MyApp) getApplication();
		getregid = myapp.getregid();
		net = new Intentnet();
		intview();
		imageYzm();
	}

	private void intview() {
		
		findViewById(R.id.avregister_image_back).setOnClickListener(this);
		findViewById(R.id.avregister_text_backload).setOnClickListener(this);
		mEphone = (EditText) findViewById(R.id.avregister_edit_phone);
		mTcode = (TextView) findViewById(R.id.avregister_text_code);
		mTok = (TextView) findViewById(R.id.avregister_text_ok);
		mT1 = (TextView) findViewById(R.id.register_text1);//��������
		mT2 = (TextView) findViewById(R.id.register_text2);
		mIg1 = (ImageView) findViewById(R.id.register_icon1);//����ͼ��
		mIg2 = (ImageView) findViewById(R.id.register_icon2);//��ҵͼ��
		showview = findViewById(R.id.register_geren_show);
		showview1 = findViewById(R.id.register_geren_show1);
		mRel_qiye = (RelativeLayout) findViewById(R.id.reageister_relative_qiye);
		mRel_gren = (RelativeLayout) findViewById(R.id.reageister_relative_geren);
		mRel_qiye.setOnClickListener(this);
		mRel_gren.setOnClickListener(this);
		mTok.setOnClickListener(this);
		mEnamesd = (EditText) findViewById(R.id.avregister_edit_namesd);
		mRelativ = (RelativeLayout) findViewById(R.id.avregister_frame);
		mEokcode = (EditText) findViewById(R.id.avregister_edit_code);
		mEpsw = (EditText) findViewById(R.id.avregister_edit_newpsw);
		mEdoublepsw = (EditText) findViewById(R.id.avregister_edit_doublepsw);
		mLinear = findViewById(R.id.avregister_linear_qiye);
		mTcode.setOnClickListener(this);
		mEyaoqing = (EditText) findViewById(R.id.avregister_edit_yaoqing);
		mEbankno = (EditText) findViewById(R.id.avregister_edit_bankno);
		mEkaihuhang = (EditText) findViewById(R.id.avregister_edit_kaihuhang);
		mEqiyename = (EditText) findViewById(R.id.avregister_edit_qiyename);
		mEzhizhao = (EditText) findViewById(R.id.avregister_edit_zhizhao);
		imageCode = (ImageView) findViewById(R.id.avregister_image_code);
		editimageCode = (EditText) findViewById(R.id.avregister_edit_img);
		String appname=getResources().getString(R.string.oem_app_name);
		user_from= Constant.USER_FROM.get(appname);
		if (!appname.equals("中财在线")){
			mEyaoqing.setHint("邀请人手机号（必填）");
			mEdoublepsw.setHint("邀请人手机号（必填）");
		}
		imageCode.setOnClickListener(this);
	}
	
	private void getdatacode(String phone ) {
		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(RegisterActivity.this);    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "Public");
		params.put("a", "sendCode");
		params.put("username", phone);
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("短信", "的"+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						Toast.makeText(RegisterActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
						Thread thread = new Thread(runnableRef);  
		                thread.start();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Log.e("response", "失败"+responseString);
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mRelativ.setVisibility(View.VISIBLE);
//				Message msg = new Message();
//        		msg.what = 1;//��������
//        		mHandler.sendMessage(msg);
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				mTcode.setClickable(true);
				mRelativ.setVisibility(View.GONE);
				Log.e("短信", "的");
//				Message msg = new Message();
//        		msg.what = 2;//�رն���
//        		mHandler.sendMessage(msg);
			}
		});
	}

	private void registerphone(final String number, String code, final String psw) {

		AsyncHttpClient ahc = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(RegisterActivity.this);    
        ahc.setCookieStore(myCookieStore); 
		RequestParams params = new RequestParams();
		params.put("g", "api");
		params.put("m", "user");
		params.put("a", "register");
		params.put("username", number);
		params.put("code", code);
		params.put("password", psw);
		params.put("registerid", JPushInterface.getRegistrationID(this));
		params.put("user_from",user_from);
		if(qiyeornot == false ){
			params.put("identity_type", "1");
			params.put("key", psws);
			params.put("user_nicename", user_nicename);
		}else{
			params.put("identity_type", "2");
			params.put("user_nicename", qiyename);
			params.put("bus_licence", zhizhao);
			params.put("bank_name", kaihuhang);
			params.put("card_no", bnkno);
			params.put("key", yaoqing);
		}
		ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				Log.e("response", ""+response);
				try {
					String flag = response.getString("flag");
					if(flag.equals("success")){
						list.add(number);
						list.add(psw);
						Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(RegisterActivity.this,LoadActivity.class);
						intent.putStringArrayListExtra("result", list);
						setResult(656, intent);
						finish();
					}else if(flag.equals("unknow")){
						String string = response.getString("info");
						Toast.makeText(RegisterActivity.this, ""+string, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
//				Message msg = new Message();
//        		msg.what = 1;//��������
//        		mHandler.sendMessage(msg);
				mTok.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.rect_lightgray));
				mTok.setClickable(false);
				mRelativ.setVisibility(View.VISIBLE);
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure(statusCode, headers, responseString, throwable);
				Log.e("response", "失败"+responseString);
				Toast.makeText(RegisterActivity.this, "注册失败！", Toast.LENGTH_SHORT).show();
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
//				Message msg = new Message();
//        		msg.what = 2;//�رն���
//        		mHandler.sendMessage(msg);
//				mBar.clearAnimation();
				mTok.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.rect_lightred));
				mTok.setClickable(true);
				mRelativ.setVisibility(View.GONE);
//				Log.e("response", "���");
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avregister_text_ok:
//			mEyaoqing,mEbankno,mEkaihuhang,mEqiyename,mEzhizhao;
			String number = mEphone.getText().toString().trim();
			String code = mEokcode.getText().toString().trim();
			String psw = mEpsw.getText().toString().trim();
			psws = ""+mEdoublepsw.getText().toString().trim();
			yaoqing = mEyaoqing.getText().toString().trim();
			bnkno = mEbankno.getText().toString().trim();
			kaihuhang = mEkaihuhang.getText().toString().trim();
			qiyename = mEqiyename.getText().toString().trim();
			zhizhao = mEzhizhao.getText().toString().trim();
			user_nicename = mEnamesd.getText().toString().trim();
			
			if(qiyeornot == false){
				if(number.equals("") || null == number){
					Toast.makeText(RegisterActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
				}else if(net.isMobile(number) == false){
					Toast.makeText(RegisterActivity.this, "非法的手机号", Toast.LENGTH_SHORT).show();
				}else if(code.equals("") || null == code){
					Toast.makeText(RegisterActivity.this, "请输入手机验证码！", Toast.LENGTH_SHORT).show();
				}else if(psw.equals("") || null == psw){
					Toast.makeText(RegisterActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
				}else if(user_nicename.equals("") || null == user_nicename){
					Toast.makeText(RegisterActivity.this, "名字不", Toast.LENGTH_SHORT).show();
				} else if(!psw.equals("") && psw.length() < 6 ){
					Toast.makeText(RegisterActivity.this, "密码数必须大于6位！", Toast.LENGTH_SHORT).show();
				}else{
					if (!(user_from==1)){
						if(psws.equals("")||null==psws){
							Toast.makeText(RegisterActivity.this, "邀请人手机号码不能为空！", Toast.LENGTH_SHORT).show();
						}else if(!psws.equals("") && net.isMobile(psws) == false){
							Toast.makeText(RegisterActivity.this, "邀请人手机号码不合法！", Toast.LENGTH_SHORT).show();
						}else {
							Log.e("registerphone","registerphone1111");
							registerphone(number,code,psw);
						}
					}else {
						Log.e("registerphone","registerphone3333");
						registerphone(number,code,psw);
					}

				}
			}else{
				if(number.equals("") || null == number){
					Toast.makeText(RegisterActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
				}else if(net.isMobile(number) == false){
					Toast.makeText(RegisterActivity.this, "非法的手机号", Toast.LENGTH_SHORT).show();
				}else if(code.equals("") || null == code){
					Toast.makeText(RegisterActivity.this, "请输入手机验证码！", Toast.LENGTH_SHORT).show();
				}else if(psw.equals("") || null == psw){
					Toast.makeText(RegisterActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
				}else if(qiyename.equals("")){
					Toast.makeText(RegisterActivity.this, "企业名称不能为空！", Toast.LENGTH_SHORT).show();
				}else if(zhizhao.equals("")){
					Toast.makeText(RegisterActivity.this, "请输入营业执照！", Toast.LENGTH_SHORT).show();
				}else if(kaihuhang.equals("")){
					Toast.makeText(RegisterActivity.this, "请输入开户行", Toast.LENGTH_SHORT).show();
				}else if(bnkno.equals("")){
					Toast.makeText(RegisterActivity.this, "请输入银行账号！", Toast.LENGTH_SHORT).show();
				}else{
					 if(!(user_from==1)){
						if(yaoqing.equals("")||null==yaoqing){
							Toast.makeText(RegisterActivity.this, "邀请人手机号码不能为空！", Toast.LENGTH_SHORT).show();
						}else if(!yaoqing.equals("") && net.isMobile(yaoqing) == false){
							Toast.makeText(RegisterActivity.this, "邀请人手机号码不合法！", Toast.LENGTH_SHORT).show();
						}else{
							Log.e("registerphone","registerphone44444");
							registerphone(number,code,psw);
						}
					}else {
						 Log.e("registerphone","registerphone22222");
						 registerphone(number,code,psw);
					 }

				}
			}

			break;
			
		case R.id.avregister_image_back:
			finish();
			break;
			
		case R.id.reageister_relative_qiye:
			mLinear.setVisibility(View.VISIBLE);
			showview.setVisibility(View.GONE);
			showview1.setVisibility(View.GONE);
			mRel_gren.setBackgroundColor(getResources().getColor(R.color.white));
			mRel_qiye.setBackgroundColor(getResources().getColor(R.color.lightred));
			mIg1.setImageDrawable(getResources().getDrawable(R.drawable.avload_image_geren));
			mT1.setTextColor(getResources().getColor(R.color.fmuserline));
			mIg2.setImageDrawable(getResources().getDrawable(R.drawable.avload_image_qiye1));
			mT2.setTextColor(getResources().getColor(R.color.white));
			qiyeornot = true;
			break;
			
		case R.id.reageister_relative_geren:
			mLinear.setVisibility(View.GONE);
			showview.setVisibility(View.VISIBLE);
			showview1.setVisibility(View.VISIBLE);
			mRel_gren.setBackgroundColor(getResources().getColor(R.color.lightred));
			mRel_qiye.setBackgroundColor(getResources().getColor(R.color.white));
			mIg1.setImageDrawable(getResources().getDrawable(R.drawable.avload_image_geren1));
			mT1.setTextColor(getResources().getColor(R.color.white));
			mIg2.setImageDrawable(getResources().getDrawable(R.drawable.avload_image_qiye));
			mT2.setTextColor(getResources().getColor(R.color.fmuserline));
			qiyeornot = false;
			break;
			
		case R.id.avregister_text_backload:
			finish();
			break;


		case R.id.avregister_image_code:
			if (!fastClick()){
				imageYzm();
			}
			break;

		case R.id.avregister_text_code:
			String phone = mEphone.getText().toString().trim();
			String imageCode = editimageCode.getText().toString().trim();
			Intentnet intentnet = new Intentnet();
			if(phone.equals("") || null == phone){
				Toast.makeText(RegisterActivity.this, "手机号码不能为空！", Toast.LENGTH_SHORT).show();
			}else if(intentnet.isMobile(phone) == false){
				Toast.makeText(RegisterActivity.this, "手机号码不正确！", Toast.LENGTH_SHORT).show();
			}else if(TextUtils.isEmpty(imageCode)){
				Toast.makeText(RegisterActivity.this, "请输入图形验证码！", Toast.LENGTH_SHORT).show();
			}else{
				Log.e("图形验证码11","图形验证码11");
//				mTcode.setClickable(false);
				if (!fastClick()){
					mydialog=Util.createLoadingDialog(RegisterActivity.this);
					yzm(phone,imageCode);
				}
			}
			break;

		default:
			break;
		}
	}

	//图形验证码 请求 （防短信轰炸）
	private void imageYzm() {
		registrationID=String.valueOf(System.currentTimeMillis());
		String url=Constant.IMAGEYZM+registrationID;
		Log.e("imageYzm",url);
		Glide.with(this)
				.load(url)
				.into(imageCode);
	}
	//图形验证码后短信验证码
	private void yzm(String mobile,String imcode) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("mobile",mobile);
		params.put("code",imcode);
		params.put("token",registrationID);
		params.put("user_from",user_from);
		Log.e("图形验证码后短信验证码arams",params.toString());
		Log.e("图形验证码后短信验证码url",Constant.DXYZM);
		//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
		ahc.post(Constant.DXYZM, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				Util.closeDialog(mydialog);
				//判断状态码
				if(i == 200){
					//获取结果
					try {
						String result = new String(bytes, "utf-8");
						//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
						Log.e("图形验证码后短信验证码Result", result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String flag = jsonObject.getString("flag");
							if(flag.equals("success")){
								Toast.makeText(RegisterActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
								Thread thread = new Thread(runnableRef);
								thread.start();
							}else {
								if (!(jsonObject.getJSONObject("data").length()==0)){
									mAlertView=new AlertView("提示",jsonObject.getJSONObject("data").getString("data"), null, new String[]{"确定"}, null, RegisterActivity.this, AlertView.Style.Alert,null);
									mAlertView.show();
								}

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
				Util.closeDialog(mydialog);
			}
		});
	}
	public boolean fastClick() {
		if (System.currentTimeMillis() - lastClick < 1000) {
			Toast.makeText(RegisterActivity.this,"不要点击过快！",Toast.LENGTH_SHORT).show();
			return true;
		}
		lastClick = System.currentTimeMillis();
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mAlertView != null && mAlertView.isShowing()) {
				mAlertView.dismiss();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);

	}
}
